//
//  QXNSUrlConnection.m
//  CommunityNannyO2O
//
//  Created by Apple on 15/7/18.
//  Copyright (c) 2015年 Apple. All rights reserved.
//

#import "QXNSUrlConnection.h"
#import "SVProgressHUD/SVProgressHUD.h"
#import "APIErrorCodeMessage.h"
#import <CommonCrypto/CommonCryptor.h>
#import "AppConfig.h"
#import "SBJSON.h"
#import "NSString+AESCrypt.h"
#import "MBProgressHUD+YC.h"
//#import "NSString+AESCrypt.h"
//#import "NSData+AESCrypt.h"
//#import "GTMBase64.h"
@implementation QXNSUrlConnection
@synthesize QXUrlDelegate;

/*
 *当接收到服务器的响应（连通了服务器）时会调用
 */
-(id)init
{
    if ( self = [super init] )
    {
        // Class-specific initializations
    }
    return self;
}
-(void)sendAPIWithUrl:(NSURL *)url AndMethod:(NSString *)method AndDataBody:(NSString *)dataBodyString
{
    
  //  NSLog(@"%@",self.QXUrlDelegate);
    NSMutableURLRequest *request=[NSMutableURLRequest  requestWithURL:url];
    request.timeoutInterval=20.0;
    //忽略缓存 直接读取网络原始链接
    request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    //设置POST请求各项参数
    [request setHTTPMethod:method];
    NSData *data = [dataBodyString dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    //使用代理发送异步请求
    NSURLConnection *connection=[NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
   // NSLog(@"已经发出请求");
}
#pragma mark- NSURLConnectionDataDelegate代理方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
   // NSLog(@"接收到服务器的响应");
    //初始化数据
    self.responseData=[NSMutableData data];
}
/*
 *当接收到服务器的数据时会调用（可能会被调用多次，每次只传递部分数据）
 */
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //NSLog(@"接收到服务器的数据");
    //拼接数据
    [self.responseData appendData:data];
  //  NSLog(@"%lu---%@--",(unsigned long)self.responseData.length,[NSThread currentThread]);
    
}
/*
 *当服务器的数据加载完毕时就会调用
 */
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
   // NSLog(@"%@",self.QXUrlDelegate);
   // NSLog(@"服务器的数据加载完毕");
    //隐藏HUD
    [SVProgressHUD dismiss];
    //处理服务器返回的所有数据
    NSString *stringUTF  = [[NSString alloc]initWithData:self.responseData encoding:NSUTF8StringEncoding];
    NSString *string = [stringUTF AES256DecryptWithKey:APPKEY];
    NSError *error;
    SBJSON *sbJson = [[SBJSON alloc]init];
    NSDictionary *dic = [sbJson objectWithString:string];
    
    if (error)  
    {//json解析失败
        [SVProgressHUD showErrorWithStatus:@"数据返回失败"];
        return;
    }else
    {//json解析成功
      //  NSLog(@"%@",[dic objectForKey:@"code"]);
        
        if(!([[dic objectForKey:@"code"] integerValue] == 200))
        {//接口请求错误
//            [SVProgressHUD showErrorWithStatus:[self decodeErrorCode:[dic objectForKey:@"code"]]];
            id JsonDic = [dic objectForKey:@"message"];
            [self.QXUrlDelegate GetFailResponse:JsonDic andTag:self.tag];
            return;
        }else
        {
            id JsonDic = [dic objectForKey:@"data"];
         //   NSLog(@"%@",self.QXUrlDelegate);
            [self.QXUrlDelegate GetSuccessResponse:JsonDic andTag:self.tag ];
            
            
            id message = [dic objectForKey:@"message"];
            [self.QXUrlDelegate GetSuccessMessage:message andTag:self.tag ];
        }
        
        
    }
    //NSLog(@"%lu---%@--",(unsigned long)self.responseData.length,[NSThread currentThread]);
}
/*
 *解析服务器端错误码
 */
-(NSString *)decodeErrorCode:(NSString *)ErrorCode
{
    NSString *returnMessage;
    switch ([ErrorCode intValue])
    {
        case 0:
            returnMessage = FailMessage;
            break;
        case -1:
            returnMessage = ParameterError;
            break;
        case -2:
            returnMessage = Decrypt;
            break;
        case -3:
            returnMessage = JsonError;
            break;
        case -4:
            returnMessage = UserUnFound;
            break;
        case -5:
            returnMessage = LoacalError;
            break;
        case -6:
            returnMessage = OrderFromError;
            break;
        case -7:
            returnMessage = IntegralError;
            break;
        case -8:
            returnMessage = IntegralLessError;
            break;
        case -9:
            returnMessage = CouponError;
            break;
        case -10:
            returnMessage = PointsError;
            break;
        case -11:
            returnMessage = IntegralAddError;
            break;
        case -12:
            returnMessage = ShoppingCartAddError;
            break;
        case -13:
            returnMessage = CommentError;
            break;
        case -14:
            returnMessage = QRError;
            break;
        case -15:
            returnMessage = MessageGetError;
            break;
        case -16:
            returnMessage = ShoppingCarthasError;
        default:
            break;
    }
    return returnMessage;
}
/*
 *请求错误（失败）的时候调用（请求超时\断网\没有网\，一般指客户端错误）
 */
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
   // NSLog(@"请求错误");
   
    [MBProgressHUD hideHUD];
    //隐藏HUD
    //[SVProgressHUD dismiss];
   // [SVProgressHUD showErrorWithStatus:@"网络繁忙，请稍后重试！"];
    [MBProgressHUD showError:@"网络繁忙，请稍后重试！"];


}
- (NSData  *)AES256ParmDecryptWithKey:(NSString *)key andDataString:(NSData *)data  //解密
{
    char keyPtr[kCCKeySizeAES128+1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    char ivPtr[kCCBlockSizeAES128 + 1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [[NSString stringWithFormat:@"1234567891011120"] getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeAES128,
                                          ivPtr,
                                          [data bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        return  [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted] ;
    }
    free(buffer);
    return nil;
}
- (NSData *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv andDataString:(NSData *)data
{//解密
    NSString *s = @"8856a52e47f4caf4d79041be469e30fb";
    NSMutableData *data2 = [NSMutableData dataWithCapacity:s.length/2];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [s length] / 2; i++) {
        byte_chars[0] = [s characterAtIndex:i*2];
        byte_chars[1] = [s characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [data2 appendBytes:&whole_byte length:1];
    }
    char keyPtr[kCCKeySizeAES128 + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    char ivPtr[kCCBlockSizeAES128 + 1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data2 length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesCrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(operation,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          ivPtr,
                                          [data2 bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *data22 =[NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        return [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
    }
    free(buffer);
    return nil;
}

@end
